<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="优惠券名称" prop="couponName">
        <el-input
          v-model="queryParams.couponName"
          placeholder="请输入优惠券名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="优惠券类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择优惠券类型" clearable size="small">
          <el-option
            v-for="dict in couponTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="优惠券状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择优惠券状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="使用范围" prop="availableGoods">
        <el-select v-model="queryParams.availableGoods" placeholder="请选择使用范围" clearable size="small">
          <el-option
            v-for="dict in availableGoodsOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['market:coupon:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['market:coupon:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['market:coupon:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="couponList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="优惠券名称" align="center" prop="couponName" />
      <el-table-column label="使用范围" align="center" prop="availableGoods">
        <template slot-scope="scope">
          <dict-tag :options="availableGoodsOptions" :value="scope.row.availableGoods"/>
        </template>
      </el-table-column>
      <el-table-column label="优惠券类型" align="center" prop="type" >
        <template slot-scope="scope">
          <dict-tag :options="couponTypeOptions" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="优惠金额/折扣" align="center" prop="deductionAmount" />
      <el-table-column label="订单可使用条件" align="center" prop="availableAmount" >
        <template slot-scope="scope">
          <div v-if="scope.row.unit == '0'">
            {{scope.row.availableAmount}}元
          </div>
          <div v-else>
            {{Math.floor(scope.row.availableAmount)}}件
          </div>
        </template>
      </el-table-column>
      <el-table-column label="过期类型" align="center" prop="expirationType" >
        <template slot-scope="scope">
          <dict-tag :options="expirationTypeOptions" :value="scope.row.expirationType"/>
        </template>
      </el-table-column>
      <el-table-column label="过期天数" align="center" prop="expirationDays" >
        <template slot-scope="scope">
          {{scope.row.expirationType == 0?scope.row.expirationDays : ''}}
        </template>
      </el-table-column>
      <el-table-column label="使用日期" align="center" prop="beginTime" width="180">
        <template slot-scope="scope">
          {{scope.row.expirationType == 1?scope.row.beginTime+ '至' +scope.row.endTime : ''}}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['market:coupon:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['market:coupon:remove']"
          >删除</el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['system:user:resetPwd', 'system:user:edit']">
                <span class="el-dropdown-link">
                  <i class="el-icon-d-arrow-right el-icon--right"></i>更多
                </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="scope.row.availableGoods == '1'"  command="handleEditClass" icon="el-icon-edit-outline"
                                v-hasPermi="['market:coupon:edit']">选择分类</el-dropdown-item>
              <el-dropdown-item v-if="scope.row.availableGoods == '2'" command="handleEditGoods" icon="el-icon-edit-outline"
                                v-hasPermi="['market:coupon:edit']">编辑商品</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改优惠券对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="优惠券名称" prop="couponName">
              <el-input v-model="form.couponName" placeholder="请输入优惠券名称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="优惠券数量" prop="stock">
              <el-input-number :min="1" v-model="form.stock" placeholder="请输入优惠券数量" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="订单使用条件" prop="availableAmount">
              满<el-input style="width: 50%;margin-left: 2%" v-model="form.availableAmount" placeholder="请输入订单可使用条件" />
              <el-select v-model="form.unit" placeholder="" style="width: 20%">
                <el-option
                  v-for="dict in couponUnitOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="优惠券类型" prop="type">
              <el-radio-group v-model="form.type">
                <el-radio
                  v-for="dict in couponTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="减免金额/折扣" prop="deductionAmount">
              <el-input v-model="form.deductionAmount" placeholder="请输入减免金额或折扣率，95折用0.95表示" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="过期类型" prop="expirationType">
              <el-radio-group v-model="form.expirationType">
                <el-radio
                  v-for="dict in expirationTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.expirationType == 0">
            <el-form-item label="过期天数" prop="expirationDays">
              <el-input-number :min="1" v-model="form.expirationDays" placeholder="请输入过期天数" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.expirationType == 1">
            <el-form-item label="日期范围" prop="dateRange">
              <el-date-picker
                v-model="form.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="优惠券状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="可使用商品" prop="availableGoods">
              <el-select v-model="form.availableGoods" placeholder="请选择使用范围" style="width: 100%">
                <el-option
                  v-for="dict in availableGoodsOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 编辑商品分类对话框 -->
    <el-dialog :title="title" :visible.sync="classOpen" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="优惠券名称" prop="couponName">
              {{form.couponName}}
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="选择商品分类" prop="stock">
              <treeselect style="width: 100%;"
                          v-model="form.classIds"
                          :options="goodsClassList"
                          :normalizer="normalizer"
                          :show-count="true"
                          :clearable="true"
                          :flat="true"
                          :multiple="true"
                          placeholder="请选择商品分类" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>



    <!-- 编辑商品对话框 -->
    <el-dialog :title="title" :visible.sync="goodsOpen" width="800px" append-to-body>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleGoodsEdit"
          >新增/编辑商品</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDeleteGoods"
          >批量删除</el-button>
        </el-col>
      </el-row>
      <el-table  :data="goodsList" @selection-change="handleGoodsSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="商品信息" align="center" width="370" >
          <template slot-scope="scope">
            <div style="height: 100%">
              <div style="display: inline-block;float:left;width: 80px;height: 80px"  >
                <el-image :src="baseUrl+scope.row.picturePath"></el-image>
              </div>
              <div style="display: inline-block;float:left;margin-left: 15px;height: 100%;width: 250px">
                <div style="text-align: left">{{scope.row.goodsCode}}</div>
                <div style="text-align: left">{{scope.row.name}}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="售价" align="center" prop="referencePrice"/>
        <el-table-column label="库存" align="center" prop="stock" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDeleteGoods(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="goodsTotal>0"
        :total="goodsTotal"
        :page.sync="queryGoodsParams.pageNum"
        :limit.sync="queryGoodsParams.pageSize"
        @pagination="getListGoods"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 商品选择器 -->
    <goods-selector
      ref="goodsSelector"
      :open="goodsSelector"
      :multiple="-1"
      @input="getCheckedGoods"
      @close="closeSelector"
    ></goods-selector>

  </div>
</template>

<script>
import {
  listCoupon,
  getCoupon,
  delCoupon,
  addCoupon,
  updateCoupon,
  changeCouponStatus,
  getGoodsList, addCouponGoods, delCouponGoods
} from "@/api/market/coupon";
import {listGoodsClass} from "@/api/goods/goodsClass";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import GoodsSelector from "@/views/goods/goods/goodsSelector";

export default {
  name: "Coupon",
  components: {
    Treeselect,
    GoodsSelector
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      goodsIds:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      goodsTotal: 0,
      // 优惠券表格数据
      couponList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //编辑商品分类弹出层
      classOpen:false,
      goodsOpen:false,
      goodsSelector:false,
      baseUrl:process.env.VUE_APP_BASE_API,
      // 优惠券状态，0为正常，1为停用字典
      statusOptions: [],
      //优惠券类型
      couponTypeOptions:[],
      //优惠券过期类型
      expirationTypeOptions:[],
      //使用范围
      availableGoodsOptions:[],
      couponUnitOptions:[],
      // 商品分类数据
      goodsClassList: [],
      goodsList:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        couponName: null,
        type: null,
        status: null,
        availableGoods: null
      },
      queryGoodsParams: {
        pageNum: 1,
        pageSize: 10,
        id:null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        couponName: [
          { required: true, message: "优惠券名称不能为空", trigger: "blur" },
          { max: 20, message: '优惠券名称长度不能超过20个字符', trigger: 'blur' }
        ],
        stock: [
          { required: true, message: "优惠券数量不能为空", trigger: "blur" },
          { pattern: /^[0-9]\d*$/, message: "数量必须为正整数", trigger: "blur" },
        ],
        availableAmount: [
          { required: true, message: "订单可使用条件不能为空", trigger: "blur" },
          { pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,message: "金额格式不正确",trigger: "blur" }
        ],
        type: [
          { required: true, message: "优惠券类型不能为空", trigger: "change" }
        ],
        deductionAmount: [
          { required: true, message: "减免金额或折扣率不能为空", trigger: "blur" },
          { pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,message: "减免金额/折扣率格式不正确",trigger: "blur" }
        ],
        expirationType: [
          { required: true, message: "过期类型不能为空", trigger: "change" }
        ],
        availableGoods: [
          { required: true, message: "可使用商品不能为空", trigger: "change" }
        ],
        expirationDays: [
          { required: true, message: "过期天数不能为空", trigger: "blur" },
          { pattern: /^[0-9]\d*$/, message: "过期天数必须为正整数", trigger: "blur" },
        ],
        dateRange:[
          { required: true, message: "日期范围不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("store_common_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("coupon_type").then(response => {
      this.couponTypeOptions = response.data;
    });
    this.getDicts("coupon_unit").then(response => {
      this.couponUnitOptions = response.data;
    });
    this.getDicts("coupon_expiration_type").then(response => {
      this.expirationTypeOptions = response.data;
    });
    this.getDicts("available_goods").then(response => {
      this.availableGoodsOptions = response.data;
    });
    this.getGoodsClassList();
  },
  methods: {
    /** 查询优惠券列表 */
    getList() {
      this.loading = true;
      listCoupon(this.queryParams).then(response => {
        this.couponList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询商品分类列表 */
    getGoodsClassList() {
      listGoodsClass().then(response => {
        this.goodsClassList = this.handleTree(response.data, "id");
      });
    },
    //treeSelect自定义键名
    normalizer(node) {
      return {
        id: node.id,
        label: node.className,
        children: node.children,
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.classOpen = false;
      this.goodsOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        extAppid: null,
        couponName: null,
        stock: null,
        availableAmount: null,
        unit: "0",
        type: "0",
        deductionAmount: null,
        expirationType: "0",
        expirationDays: null,
        dateRange:[],
        beginTime: null,
        endTime: null,
        status: "0",
        availableGoods: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 多选框选中数据
    handleGoodsSelectionChange(selection) {
      this.goodsIds = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleEditClass":
          this.handleEditClass(row);
          break;
        case "handleEditGoods":
          this.handleEditGoods(row);
          break;
        default:
          break;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加优惠券";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCoupon(id).then(response => {
        this.form = response.data;
        if(this.form.expirationType == 1){
          this.form.dateRange=[this.form.beginTime,this.form.endTime]
        }
        this.open = true;
        this.title = "修改优惠券";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCoupon(this.form).then(response => {
              this.msgSuccess("操作成功");
              this.open = false;
              this.classOpen = false;
              this.getList();
            });
          } else {
            if(this.form.expirationType == 1){
              this.form.beginTime=this.form.dateRange[0]
              this.form.endTime=this.form.dateRange[1]
            }
            addCoupon(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除优惠券编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCoupon(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    // 状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$confirm('确认要"' + text + '""' + row.couponName + '"优惠券吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return changeCouponStatus(row.id, row.status);
      }).then(() => {
        this.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    handleEditClass(row){
      this.reset();
      const id = row.id || this.ids
      getCoupon(id).then(response => {
        this.form = response.data;
        this.title="选择商品分类";
        this.classOpen=true;
      });
    },
    handleEditGoods(row){
      this.queryGoodsParams.id = row.id;
      this.getListGoods();
      this.title = "优惠券商品管理"
      this.goodsOpen = true;
    },
    getListGoods(){
      getGoodsList(this.queryGoodsParams).then(response => {
        this.goodsList = response.rows;
        this.goodsTotal = response.total;
      });
    },
    handleGoodsEdit(){
      this.goodsSelector=true;
    },
    handleDeleteGoods(row){
      const ids = row.id || this.goodsIds;
      this.$confirm('是否确认删除选中的优惠券商品吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delCouponGoods(ids);
      }).then(() => {
        this.getListGoods();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    //选择器确定选择
    getCheckedGoods(checkedGoodsList){
      let goodsIds = [];
      checkedGoodsList.forEach(goods=>{
        goodsIds.push(goods.id)
      })
      //数据处理
      if(this.goodsOpen && goodsIds.length > 0 ){
        const form={
          id:this.queryGoodsParams.id,
          goodsIds:goodsIds
        }
        addCouponGoods(form).then(response => {
          this.getListGoods();
        })
      }
    },
    //关闭选择器
    closeSelector(){
      this.goodsSelector=false;
    },
  }
};
</script>
